package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.FltVehicleInfo;
import com.ruoyi.system.mapper.FltVehicleInfoMapper;
import com.ruoyi.system.service.IFltVehicleInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 检测数据Service业务层处理
 */
@Service
public class FltVehicleInfoServiceImpl implements IFltVehicleInfoService {

    @Autowired
    private FltVehicleInfoMapper fltVehicleMapper;

    @Override
    public FltVehicleInfo getByCheckNo(String checkNo) {
        String tableName = "flt_vehicle_info_" + StrUtil.subPre(checkNo, 6);
        return fltVehicleMapper.getByCheckNo(tableName, checkNo);
    }

    /**
     * 查询检测数据列表
     *
     * @param fltVehicle 检测数据
     * @return 检测数据
     */
    @Override
    public List<FltVehicleInfo> selectFltVehicleList(FltVehicleInfo fltVehicle) {
        fltVehicle.setTableName("flt_vehicle_info" + "_" + this.yyyyMM(fltVehicle.getCheckTime()));
        return fltVehicleMapper.selectFltVehicleList(fltVehicle);
    }

    /***
     * 更新保存检测数据信息
     */
    @Override
    public void saveFltVehicle(FltVehicleInfo fltVehicle) {
        if (this.existByUniqueId(fltVehicle)) {
            this.update(fltVehicle);
        } else {
            this.insert(fltVehicle);
        }
    }

    @Override
    public boolean existByUniqueId(FltVehicleInfo fltVehicle) {
        fltVehicle.setTableName("flt_vehicle_info" + "_" + this.yyyyMM(fltVehicle.getCheckTime()));
        return fltVehicleMapper.countByUniqueId(fltVehicle) > 0;
    }

    /**
     * 新增检测数据
     */
    @Override
    public synchronized FltVehicleInfo insert(FltVehicleInfo fltVehicle) {
        fltVehicle.setTableName("flt_vehicle_info" + "_" + this.yyyyMM(fltVehicle.getCheckTime()));
        fltVehicleMapper.insert(fltVehicle);
        return fltVehicle;
    }

    /**
     * 更新检测数据
     */
    @Override
    public FltVehicleInfo update(FltVehicleInfo fltVehicle) {
        fltVehicle.setTableName("flt_vehicle_info" + "_" + this.yyyyMM(fltVehicle.getCheckTime()));
        fltVehicleMapper.update(fltVehicle);
        return fltVehicle;
    }

    private String yyyyMM(Date checkTime) {
        String yyyyMM = DateUtils.parseDateToStr("yyyyMM", checkTime);
        if (StringUtils.isBlank(yyyyMM)) {
            yyyyMM = DateUtils.dateTimeNow("yyyyMM");
        }
        return yyyyMM;
    }

}
